package com.atguigu.gmall.realtime.utils;

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;

import java.io.IOException;

/**
 * @author Felix
 * @date 2023/7/28
 * 操作kafka的工具类
 */
public class KafkaUtil {
    private static final String KAFKA_SERVER = "hadoop102:9092,hadoop103:9092,hadoop104:9092";

    //获取kafkaSource
    public static KafkaSource<String> getKafkaSource(String topic, String groupId) {
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
            .setBootstrapServers(KAFKA_SERVER)
            .setTopics(topic)
            .setGroupId(groupId)
            //在生产环境中，如果要想保证数据一致性，预提交的数据不应该读取，所以设置隔离级别为read_committed
            // .setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG,"read_committed")
            //在生产环境，推荐使用如下配置，先从flink检查点钟维护偏移量位置开始消费，如果没有找到，再从kakfa的主题最新位置开始消费
            // .setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.LATEST))
            //在学习阶段，直接从kafka的最新位置开始消费
            .setStartingOffsets(OffsetsInitializer.latest())
            //如果使用SimpleStringSchema进行反序列化的话，如果读取到的消息为空，它处理不了，需要我们自己重新实现反序列化
            // .setValueOnlyDeserializer(new SimpleStringSchema())
            .setValueOnlyDeserializer(new DeserializationSchema<String>() {
                @Override
                public String deserialize(byte[] message) throws IOException {
                    if (message != null) {
                        return new String(message);
                    }
                    return null;
                }

                @Override
                public boolean isEndOfStream(String nextElement) {
                    return false;
                }

                @Override
                public TypeInformation<String> getProducedType() {
                    return TypeInformation.of(String.class);
                }
            })
            .build();
        return kafkaSource;
    }

    //获取kafkaSink
    public static KafkaSink<String> getKafkaSink(String topic) {
        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
            .setBootstrapServers(KAFKA_SERVER)
            .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                .setTopic(topic)
                .setValueSerializationSchema(new SimpleStringSchema())
                .build()
            )
            //注意：如果要保证一致性，需要设置DeliveryGuarantee.EXACTLY_ONCE，在底层会开启事务
            //如果一个应用中有多条流，需要设置setTransactionalIdPrefix
            //事务的超时时间，应该大于检查点的超时时间
            //消费者端不能读取预提交数据  需要设置.setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG,"read_committed")
            // .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
            // .setTransactionalIdPrefix("xxxx")
            // .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000+"")
            .build();
        return kafkaSink;
    }

    //获取从topic_db主题中读取数据 创建动态表的建表语句
    public static String getTopicDbDDL(String groupId) {
        return "CREATE TABLE topic_db (\n" +
            "   `database` string,\n" +
            "   `table` string,\n" +
            "   `type` string,\n" +
            "   ts string,\n" +
            "   `data` MAP<string, string>,\n" +
            "   `old`  MAP<string, string>,\n" +
            "   proc_time as PROCTIME()\n" +
            ") " + getKafkaDDL("topic_db", groupId);
    }

    //获取kaka连接器连接属性
    public static String getKafkaDDL(String topic, String groupId) {
        return " WITH (\n" +
            "  'connector' = 'kafka',\n" +
            "  'topic' = '" + topic + "',\n" +
            "  'properties.bootstrap.servers' = '" + KAFKA_SERVER + "',\n" +
            "  'properties.group.id' = '" + groupId + "',\n" +
            "  'scan.startup.mode' = 'latest-offset',\n" +
            "  'format' = 'json'\n" +
            ")";
    }

    //获取upsert-kafka连接器连接属性
    public static String getUpsertKafkaDDL(String topic) {
        return " WITH (\n" +
            "  'connector' = 'upsert-kafka',\n" +
            "  'topic' = '" + topic + "',\n" +
            "  'properties.bootstrap.servers' = '" + KAFKA_SERVER + "',\n" +
            "  'key.format' = 'json',\n" +
            "  'value.format' = 'json'\n" +
            ")";
    }

    //获取kafkaSink  ---- 将流中的数据写到kafka的不同的主题
    public static <T>KafkaSink<T> getKafkaSinkBySchema(KafkaRecordSerializationSchema<T> kafkaRecordSerializationSchema) {
        KafkaSink<T> kafkaSink = KafkaSink.<T>builder()
            .setBootstrapServers(KAFKA_SERVER)
            .setRecordSerializer(
                kafkaRecordSerializationSchema
            )
            //注意：如果要保证一致性，需要设置DeliveryGuarantee.EXACTLY_ONCE，在底层会开启事务
            //如果一个应用中有多条流，需要设置setTransactionalIdPrefix
            //事务的超时时间，应该大于检查点的超时时间
            //消费者端不能读取预提交数据  需要设置.setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG,"read_committed")
            // .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
            // .setTransactionalIdPrefix("xxxx")
            // .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000+"")
            .build();
        return kafkaSink;
    }
}
